package com.yuantu.judiciary.serviceimpl;

import com.alibaba.fastjson2.JSON;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.payment.common.models.AlipayTradeCreateResponse;
import com.alipay.easysdk.payment.page.Client;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import com.google.gson.Gson;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayResponse;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayWithRequestPaymentResponse;
import com.wechat.pay.java.service.payments.model.Transaction;
import com.yuantu.judiciary.common.SysCode;
import com.yuantu.judiciary.constant.Regulation;
import com.yuantu.judiciary.dao.*;
import com.yuantu.judiciary.exception.enums.*;
import com.yuantu.judiciary.model.api.MonitorEnterAddDTO;
import com.yuantu.judiciary.model.api.MonitorPersonAddDTO;
import com.yuantu.judiciary.model.domain.*;
import com.yuantu.judiciary.model.dto.AddOrderDTO;
import com.yuantu.judiciary.model.dto.SendTimerAuthDataDTO;
import com.yuantu.judiciary.model.enums.*;
import com.yuantu.judiciary.model.form.*;
import com.yuantu.judiciary.model.vo.*;
import com.yuantu.judiciary.service.*;
import com.yuantu.judiciary.utils.AssertUtil;
import com.yuantu.judiciary.utils.TimeUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.*;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 套餐订单模块
 *
 * @author syw
 * @since 2023-08-14
 **/
@Service
@RequiredArgsConstructor
@Slf4j
public class VipOrderServiceImpl implements IVipOrderService {

    private static final Gson GSON = new Gson();
    private final IAccountDao accountDao;
    private final IUserInfoDao userInfoDao;
    private final IOrganizationDao organizationDao;
    private final IVipInfoDao vipInfoDao;
    private final IVipOrderDao orderDao;
    private final IVipOrderDetailDao orderDetailDao;
    private final IVipOrderNotifyDao orderNotifyDao;
    private final IApiWxPayService wxPayService;
    private final IOrgVipRecordDao orgVipRecordDao;
    private final IInvoiceInfoDao invoiceInfoDao;
    private final IApiAppAliPayService appAliPayService;
    private final IApiWapAliPayService wapAliPayService;
    private final IInviteCodeService inviteCodeService;
    private final IApiAliAppletService aliAppletService;
    private final IQueryRecordDao queryRecordDao;
    private final IApiQrcodeAliPayService apiQrcodeAliPayService;
    private final IDiscountCodeDao discountCodeDao;
    private final ISearchRecordService searchRecordService;
    private final ISmsService smsService;
    private final IOrganizationSourceDao organizationSourceDao;
    private final IOperatorService operatorService;
    private final IMembershipCardDao membershipCardDao;
    private final IMembershipCardAccountDao membershipCardAccountDao;
    private final IShowInfoDao showInfoDao;
    private final IInviteRecordDao inviteRecordDao;
    private final IInviteCodeDao inviteCodeDao;
    private final IMonitorRecordDao monitorRecordDao;
    private final IMonitorEntityDao monitorEntityDao;
    private final IOpenApiService openApiService;
    private final IVipRecordAppletDao vipRecordAppletDao;

    @Value("${spring.profiles.active}")
    private String active;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AddOrderVO add(Long accountId, AddOrderForm form) {
        VipInfoDO vipInfo = vipInfoDao.findByIdAndDeletedFalse(form.getVipId());
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(vipInfo), VipExceptionEnum.VIP_NOT_EXIST);
        AccountDO account = accountDao.findByIdAndDeletedFalse(accountId);
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(account), AccountExceptionEnum.ACCOUNT_NOT_EXIST);
        UserInfoDO userInfo = userInfoDao.findByIdAndDeletedFalse(account.getUserId());
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(userInfo), UserExceptionEnum.USER_NOT_EXIST);
        OrganizationDO organization = organizationDao.findByIdAndDeletedFalse(account.getOrganizationId());
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(organization), OrganizationExceptionEnum.ORGANIZATION_NOT_EXIST);

        inviteCodeService.bindInviteRecord(form.getCode(), organization.getId(), accountId);
        //根据来源企业折扣重新得到总价
        OrganizationSourceDO organizationSource = organizationSourceDao.findInfoByIdAndDeletedFalse(organization.getOrganizationSourceId());
        Double discount = organizationSource.getDiscount();
        Double totalPrice = vipInfo.getTotalPrice();
        double discountPrice = totalPrice;
        if (!(vipInfo.getId() == 8L || vipInfo.getId() == 13L)) {
            discountPrice = vipInfo.getTotalPrice();
            if (discount != 1) {
                discountPrice = (int) (totalPrice * discount);
            }
        }
        String tradeNo = UUID.randomUUID().toString().replace("-", "");
        log.info("总金额：" + vipInfo.getTotalPrice() + "折后价格：" + discountPrice);
        double payPrice = vipInfo.getTotalPrice() == discountPrice ?
                vipInfo.getTotalPrice() : discountPrice;
        log.info("付款金额：" + payPrice);
        PrepayResponse response = wxPayService.addOrder(new AddOrderDTO(tradeNo, vipInfo.getName(), payPrice, userInfo.getOpenId()));

        VipOrderDO order = new VipOrderDO();
        order.setVipId(form.getVipId());
        order.setVipName(vipInfo.getName());
        order.setOrganizationId(account.getOrganizationId());
        order.setTradeNo(tradeNo);
        order.setPrepayId(response.getPrepayId());
        order.setTotalPrice(payPrice);
        order.setExpiresTime(new Timestamp(System.currentTimeMillis() + 2 * 60 * 60 * 1000));
        order.setPayState(PayState.TO_PAY);
        order.setOrgType(organization.getType());
        orderDao.save(order);
        VipOrderDetailDO detail = new VipOrderDetailDO();
        detail.setOrderId(order.getId());
        detail.setTradeNo(tradeNo);
        detail.setVipName(vipInfo.getName());
        detail.setTotalPrice(vipInfo.getTotalPrice());
        detail.setUnitPrice(vipInfo.getUnitPrice());
        detail.setDuration(vipInfo.getDuration());
        detail.setQueryTotalNum(vipInfo.getQueryTotalNum());
        detail.setAccountNum(vipInfo.getAccountNum());
        detail.setOrgName(OrganizationType.ENTER.equals(organization.getType()) ? organization.getEnterName() : account.getUsername());
        detail.setUsername(account.getUsername());
        detail.setPhone(userInfo.getPhone());
        detail.setType("微信");
        detail.setOrgType(organization.getType());
        orderDetailDao.save(detail);
        log.info("创建订单号: {}, 微信预支付订单号: {}", tradeNo, response.getPrepayId());
        //如果是测试环境则屏蔽支付功能。
        if ("dev".equals(active)) {
            Transaction transaction = new Transaction();
            transaction.setOutTradeNo(tradeNo);
            transaction.setTradeState(Transaction.TradeStateEnum.SUCCESS);
            transaction.getTradeState().name();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssXXX");
            transaction.setSuccessTime(ZonedDateTime.now().format(formatter));
            //将当前时间转换成 yyyy-MM-dd'T'HH:mm:ssXXX 格式的时间字符串
            transaction.setTradeType(Transaction.TradeTypeEnum.JSAPI);
            savePayResult(transaction);
        }
        return new AddOrderVO(order.getId());
    }

    @Override
    public PrepayWithRequestPaymentResponse getParam(Long accountId, Long id) {
        AccountDO account = accountDao.findByIdAndDeletedFalse(accountId);
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(account), AccountExceptionEnum.ACCOUNT_NOT_EXIST);
        VipOrderDO order = orderDao.findOrderByIdAndCreatorIdAndDeletedFalse(id, accountId);
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(order), OrderExceptionEnum.ORDER_NOT_EXIST);
        UserInfoDO userInfo = userInfoDao.findByIdAndDeletedFalse(account.getUserId());
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(userInfo), UserExceptionEnum.USER_NOT_EXIST);
        PrepayWithRequestPaymentResponse response = wxPayService.getParam(new AddOrderDTO(order.getTradeNo(), order.getVipName(), order.getTotalPrice(), userInfo.getOpenId()));
        log.info("订单 id : {}, 订单号: {}, 下单参数: {}", order.getId(), order.getTradeNo(), GSON.toJson(response.toString()));
        return response;
    }

    @Override
    public Map<String, Object> callOrder(HttpServletRequest request) {
        Transaction transaction = wxPayService.callOrder(request);
        return savePayResult(transaction);
    }

    /**
     * 保存支付成功信息
     */
    private Map<String, Object> savePayResult(Transaction transaction) {
        Map<String, Object> res = new HashMap<>(8);
        log.info("支付回调解析结果: {}", GSON.toJson(transaction));
        //保存交易信息
        VipOrderNotifyDO notify = new VipOrderNotifyDO();
        notify.setTradeNo(transaction.getOutTradeNo());
        notify.setResult(GSON.toJson(transaction));
        orderNotifyDao.save(notify);

        if (ObjectUtils.isEmpty(transaction)) {
            res.put("code", "FAIL");
            res.put("message", "支付回调异常");
        } else {
            VipOrderDO order = orderDao.findOrderByTradeNoAndDeletedFalse(transaction.getOutTradeNo());
            if (ObjectUtils.isEmpty(order)) {
                log.info("订单号: {} 对应订单不存在", transaction.getOutTradeNo());
                res.put("code", "FAIL");
                res.put("message", "订单不存在");
                return res;
            }

            VipOrderDetailDO detail = orderDetailDao.findDetailByOrderIdAndDeletedFalse(order.getId());
            if (ObjectUtils.isEmpty(detail)) {
                log.info("订单 id : {}, 订单号: {} 详情不存在", order.getId(), order.getTradeNo());
                res.put("code", "FAIL");
                res.put("message", "订单详情不存在");
                return res;
            }
            if (PayState.SUCCESS.equals(order.getPayState())) {
                log.info("订单号: {} 已支付", order.getTradeNo());
                res.put("code", "SUCCESS");
                res.put("message", "成功");
                return res;
            }
            if ("SUCCESS".equals(transaction.getTradeState().name())) {
                // 日期转换
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssXXX");
                LocalDateTime dateTime = LocalDateTime.parse(transaction.getSuccessTime(), formatter);

                order.setPayTime(Timestamp.valueOf(dateTime));
                order.setState(transaction.getTradeState().name());
                order.setPayState(PayState.SUCCESS);
                orderDao.save(order);

                //如果是单次付费需要对可能存在的推荐码或邀请人进行积分奖励
                if (order.getId() == 8L || order.getId() == 13L) {
                    operatorService.updateHistoryScore(order);
                }

                detail.setPayTime(Timestamp.valueOf(dateTime));
                detail.setEffectiveTime(Timestamp.valueOf(dateTime));
                detail.setExpiresTime(ObjectUtils.isEmpty(detail.getDuration()) ? null : Timestamp.valueOf(dateTime.plus(detail.getDuration(), ChronoUnit.YEARS)));
                detail.setPayType(transaction.getTradeType().name());
                orderDetailDao.save(detail);

                VipRecordAppletDO vipRecordAppletDO = vipRecordAppletDao.findDistinctByAccountIdAndDeletedFalse(order.getCreatorId());
                if(ObjectUtils.isEmpty(vipRecordAppletDO)){
                    vipRecordAppletDO = new VipRecordAppletDO();
                    vipRecordAppletDO.setSearchTimes(detail.getQueryTotalNum());
                    vipRecordAppletDO.setAccountId(order.getCreatorId());
                    vipRecordAppletDao.save(vipRecordAppletDO);
                }else{
                   vipRecordAppletDO.setSearchTimes(vipRecordAppletDO.getSearchTimes() + detail.getQueryTotalNum());
                    vipRecordAppletDao.save(vipRecordAppletDO);
                }

                OrgVipRecordDO orgVipRecord = orgVipRecordDao.findRecordByOrganizationIdAndDeletedFalse(order.getOrganizationId());
                if (ObjectUtils.isEmpty(orgVipRecord)) {
                    orgVipRecord = new OrgVipRecordDO();
                    orgVipRecord.setOrganizationId(order.getOrganizationId());
                    orgVipRecord.setTotalSearchTimes(detail.getQueryTotalNum());
                    orgVipRecord.setAccountNum(detail.getAccountNum());
                    orgVipRecord.setExpiresTime(detail.getExpiresTime());
                    orgVipRecord.setBuySearchTimes(detail.getQueryTotalNum());
                    orgVipRecordDao.save(orgVipRecord);
                } else {
                    orgVipRecord.setTotalSearchTimes(orgVipRecord.getTotalSearchTimes() + detail.getQueryTotalNum());
                    orgVipRecord.setBuySearchTimes((orgVipRecord.getBuySearchTimes() == null ? 0 : orgVipRecord.getBuySearchTimes()) + detail.getQueryTotalNum());
                    if (!ObjectUtils.isEmpty(detail.getDuration())) {
                        Calendar c = Calendar.getInstance();
                        c.setTime(ObjectUtils.isEmpty(orgVipRecord.getExpiresTime()) ? new Timestamp(System.currentTimeMillis()) : orgVipRecord.getExpiresTime());
                        c.add(Calendar.YEAR, detail.getDuration());
                        orgVipRecord.setExpiresTime(new Timestamp(c.getTimeInMillis()));
                    }
                    if (orgVipRecord.getAccountNum() == null || (!ObjectUtils.isEmpty(detail.getAccountNum()) && orgVipRecord.getAccountNum() < detail.getAccountNum())) {
                        orgVipRecord.setAccountNum(detail.getAccountNum());
                    }
                    orgVipRecordDao.save(orgVipRecord);
                }

                //code 退款码请前往微信支付文档查询
                res.put("code", "SUCCESS");
                res.put("message", "成功");
            } else {
                // 日期转换
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssXXX");
                LocalDateTime dateTime = LocalDateTime.parse(transaction.getSuccessTime(), formatter);

                order.setPayTime(Timestamp.valueOf(dateTime));
                order.setState(transaction.getTradeState().name());
                order.setPayState(PayState.FAILURE);
                orderDao.save(order);

                detail.setPayTime(Timestamp.valueOf(dateTime));
                detail.setPayType(transaction.getTradeState().name());
                orderDetailDao.save(detail);

                res.put("code", "FAIL");
                res.put("message", transaction.getTradeState());
            }
        }
        return res;
    }

    @Override
    public AddOrderVO addShare(Long accountId, Long memberCardId) {

        MembershipCardDO membershipCard = membershipCardDao.findInfoByIdAndIsDeletedFalse(memberCardId);
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(membershipCard), VipExceptionEnum.MEMBERSHIP_CARD_NOT_EXIST);
        AccountDO account = accountDao.findByIdAndDeletedFalse(accountId);
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(account), AccountExceptionEnum.ACCOUNT_NOT_EXIST);
        UserInfoDO userInfo = userInfoDao.findByIdAndDeletedFalse(account.getUserId());
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(userInfo), UserExceptionEnum.USER_NOT_EXIST);
        OrganizationDO organization = organizationDao.findByIdAndDeletedFalse(account.getOrganizationId());
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(organization), OrganizationExceptionEnum.ORGANIZATION_NOT_EXIST);
        String tradeNo = UUID.randomUUID().toString().replace("-", "");
        PrepayResponse response = wxPayService.addOrder(new AddOrderDTO(tradeNo, membershipCard.getCardName(),
                membershipCard.getCardFee(), userInfo.getOpenId(), IsShare.YES.getValue()));

        VipOrderDO order = new VipOrderDO();
        order.setVipId(memberCardId);
        order.setVipName(membershipCard.getCardName());
        order.setOrganizationId(account.getOrganizationId());
        order.setTradeNo(tradeNo);
        order.setPrepayId(response.getPrepayId());
        order.setTotalPrice(membershipCard.getCardFee());
        order.setExpiresTime(new Timestamp(System.currentTimeMillis() + 2 * 60 * 60 * 1000));
        order.setPayState(PayState.TO_PAY);
        order.setOrgType(organization.getType());
        orderDao.save(order);
        VipOrderDetailDO detail = new VipOrderDetailDO();
        detail.setOrderId(order.getId());
        detail.setTradeNo(tradeNo);
        detail.setVipName(membershipCard.getCardName());
        detail.setDuration(membershipCard.getValidDays());
        detail.setQueryTotalNum(membershipCard.getQueryNum());
        detail.setAccountNum(membershipCard.getAccountNum());
        detail.setExpiresTime(ObjectUtils.isEmpty(membershipCard.getValidDays()) ? null :
                new Timestamp(System.currentTimeMillis() + membershipCard.getValidDays() * 24 * 60 * 60 * 1000));
        detail.setTotalPrice(membershipCard.getCardFee());
        detail.setUnitPrice(membershipCard.getCardFee());
        detail.setOrgName(OrganizationType.ENTER.equals(organization.getType()) ? organization.getEnterName() : account.getUsername());
        detail.setUsername(account.getUsername());
        detail.setPhone(userInfo.getPhone());
        detail.setType("微信");
        detail.setOrgType(organization.getType());
        orderDetailDao.save(detail);
        log.info("创建订单号: {}, 微信预支付订单号: {}", tradeNo, response.getPrepayId());
        return new AddOrderVO(order.getId());
    }

    @Override
    public PrepayWithRequestPaymentResponse getParamShare(Long accountId, Long id) {
        AccountDO account = accountDao.findByIdAndDeletedFalse(accountId);
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(account), AccountExceptionEnum.ACCOUNT_NOT_EXIST);
        VipOrderDO order = orderDao.findOrderByIdAndCreatorIdAndDeletedFalse(id, accountId);
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(order), OrderExceptionEnum.ORDER_NOT_EXIST);
        UserInfoDO userInfo = userInfoDao.findByIdAndDeletedFalse(account.getUserId());
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(userInfo), UserExceptionEnum.USER_NOT_EXIST);
        PrepayWithRequestPaymentResponse response = wxPayService.getParam(new AddOrderDTO(order.getTradeNo(), order.getVipName(),
                order.getTotalPrice(), userInfo.getOpenId(), IsShare.YES.getValue()));
        log.info("订单 id : {}, 订单号: {}, 下单参数: {}", order.getId(), order.getTradeNo(), GSON.toJson(response.toString()));
        return response;
    }

    @Override
    public Map<String, Object> callOrderShare(HttpServletRequest request) {

        Map<String, Object> res = new HashMap<>(8);

        Transaction transaction = wxPayService.callOrder(request);
        log.info("支付回调解析结果: {}", GSON.toJson(transaction));

        //保存交易信息
        VipOrderNotifyDO notify = new VipOrderNotifyDO();
        notify.setTradeNo(transaction.getOutTradeNo());
        notify.setResult(GSON.toJson(transaction));
        orderNotifyDao.save(notify);

        if (ObjectUtils.isEmpty(transaction)) {
            res.put("code", "FAIL");
            res.put("message", "支付回调异常");
        } else {
            VipOrderDO order = orderDao.findOrderByTradeNoAndDeletedFalse(transaction.getOutTradeNo());
            if (ObjectUtils.isEmpty(order)) {
                log.info("订单号: {} 对应订单不存在", transaction.getOutTradeNo());
                res.put("code", "FAIL");
                res.put("message", "订单不存在");
                return res;
            }

            VipOrderDetailDO detail = orderDetailDao.findDetailByOrderIdAndDeletedFalse(order.getId());
            if (ObjectUtils.isEmpty(detail)) {
                log.info("订单 id : {}, 订单号: {} 详情不存在", order.getId(), order.getTradeNo());
                res.put("code", "FAIL");
                res.put("message", "订单详情不存在");
                return res;
            }
            if (PayState.SUCCESS.equals(order.getPayState())) {
                log.info("订单号: {} 已支付", order.getTradeNo());
                res.put("code", "SUCCESS");
                res.put("message", "成功");
                return res;
            }

            if ("SUCCESS".equals(transaction.getTradeState().name())) {
                // 日期转换
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssXXX");
                LocalDateTime dateTime = LocalDateTime.parse(transaction.getSuccessTime(), formatter);

                order.setPayTime(Timestamp.valueOf(dateTime));
                order.setState(transaction.getTradeState().name());
                order.setPayState(PayState.SUCCESS);
                orderDao.save(order);

                detail.setPayTime(Timestamp.valueOf(dateTime));
                detail.setEffectiveTime(Timestamp.valueOf(dateTime));
                detail.setExpiresTime(ObjectUtils.isEmpty(detail.getDuration()) ? null : Timestamp.valueOf(dateTime
                        .plus(detail.getDuration(), ChronoUnit.YEARS)));
                detail.setPayType(transaction.getTradeType().name());
                orderDetailDao.save(detail);

                List<InviteRecordDO> existInviteRecords = inviteRecordDao.findRecordByCreatorIdAndTypeAndDeletedFalse(order.getCreatorId(),
                        InviteCodeType.INVITE);
                if (!CollectionUtils.isEmpty(existInviteRecords)) {
                    existInviteRecords.sort(Comparator.comparing(InviteRecordDO::getId, Comparator.reverseOrder()));
                    InviteRecordDO inviteRecord = existInviteRecords.get(0);
                    inviteRecord.setIsPay(true);
                    inviteRecord.setShareType(order.getVipId() == 2 ? ShareType.NORMAL.getValue() : ShareType.HIGH.getValue());
                    inviteRecordDao.save(inviteRecord);
                    //添加购买人查询次数和分享人积分

                    VipRecordAppletDO vipRecordAppletDO = vipRecordAppletDao.findDistinctByAccountIdAndDeletedFalse(order.getCreatorId());
                    if(ObjectUtils.isEmpty(vipRecordAppletDO)){
                        vipRecordAppletDO = new VipRecordAppletDO();
                        vipRecordAppletDO.setSearchTimes(detail.getQueryTotalNum());
                        vipRecordAppletDO.setAccountId(order.getCreatorId());
                        vipRecordAppletDao.save(vipRecordAppletDO);
                    }else{
                        vipRecordAppletDO.setSearchTimes(vipRecordAppletDO.getSearchTimes() + detail.getQueryTotalNum());
                        vipRecordAppletDao.save(vipRecordAppletDO);
                    }
                    OrgVipRecordDO orgVipRecord = orgVipRecordDao.findRecordByOrganizationIdAndDeletedFalse(order.getOrganizationId());
                    if (ObjectUtils.isEmpty(orgVipRecord)) {
                        orgVipRecord = new OrgVipRecordDO();
                        orgVipRecord.setOrganizationId(order.getOrganizationId());
                        orgVipRecord.setTotalSearchTimes(detail.getQueryTotalNum());
                        if (OrganizationType.ENTER.equals(detail.getOrgType())) {
                            orgVipRecord.setAccountNum(detail.getAccountNum());
                        }
                        orgVipRecord.setExpiresTime(detail.getExpiresTime());
                        orgVipRecord.setBuySearchTimes(detail.getQueryTotalNum());
                        orgVipRecordDao.save(orgVipRecord);
                    } else {
                        orgVipRecord.setTotalSearchTimes(orgVipRecord.getTotalSearchTimes() + detail.getQueryTotalNum());
                        orgVipRecord.setBuySearchTimes((orgVipRecord.getBuySearchTimes() == null ? 0 : orgVipRecord.getBuySearchTimes()) + detail.getQueryTotalNum());
                        if (!ObjectUtils.isEmpty(detail.getDuration())) {
                            Calendar c = Calendar.getInstance();
                            c.setTime(ObjectUtils.isEmpty(orgVipRecord.getExpiresTime()) ? new Timestamp(System.currentTimeMillis()) : orgVipRecord.getExpiresTime());
                            c.add(Calendar.DATE, detail.getDuration());
                            orgVipRecord.setExpiresTime(new Timestamp(c.getTimeInMillis()));
                        }
                        if (OrganizationType.ENTER.equals(detail.getOrgType())) {
                            if (orgVipRecord.getAccountNum() == null || (!ObjectUtils.isEmpty(detail.getAccountNum()) && orgVipRecord.getAccountNum() < detail.getAccountNum())) {
                                orgVipRecord.setAccountNum(detail.getAccountNum());
                            }
                        }
                        orgVipRecordDao.save(orgVipRecord);
                    }


                    MembershipCardDO membershipCard = membershipCardDao.findInfoByIdAndIsDeletedFalse(order.getVipId());
                    Long operatorId = inviteCodeDao.findCodeByInviteCodeAndTypeAndDeletedFalse(inviteRecord.getInviteCode(),
                            InviteCodeType.INVITE).getOperatorId();
                    AccountDO account = accountDao.findByIdAndDeletedFalse(operatorId);
                    Double historyScore = account.getHistoryScore();
                    account.setHistoryScore(historyScore == null ? membershipCard.getSharePoint() : historyScore + membershipCard.getSharePoint());
                    accountDao.save(account);
                    order.setHistoryScore(membershipCard.getSharePoint());
                    orderDao.save(order);
                }
                //code 退款码请前往微信支付文档查询
                res.put("code", "SUCCESS");
                res.put("message", "成功");
            } else {
                // 日期转换
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssXXX");
                LocalDateTime dateTime = LocalDateTime.parse(transaction.getSuccessTime(), formatter);

                order.setPayTime(Timestamp.valueOf(dateTime));
                order.setState(transaction.getTradeState().name());
                order.setPayState(PayState.FAILURE);
                orderDao.save(order);

                detail.setPayTime(Timestamp.valueOf(dateTime));
                detail.setPayType(transaction.getTradeState().name());
                orderDetailDao.save(detail);

                res.put("code", "FAIL");
                res.put("message", transaction.getTradeState());
            }
        }
        return res;
    }

    @Override
    public com.wechat.pay.java.service.payments.h5.model.PrepayResponse createPayPage(Long accountId, PayPageInfoVO payPageInfo) {

        MembershipCardDO membershipCard = membershipCardDao.findInfoByIdAndIsDeletedFalse(payPageInfo.getMemberCardId());
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(membershipCard), VipExceptionEnum.MEMBERSHIP_CARD_NOT_EXIST);
        AccountDO account = accountDao.findByIdAndDeletedFalse(accountId);
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(account), AccountExceptionEnum.ACCOUNT_NOT_EXIST);
        UserInfoDO userInfo = userInfoDao.findByIdAndDeletedFalse(account.getUserId());
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(userInfo), UserExceptionEnum.USER_NOT_EXIST);
        OrganizationDO organization = organizationDao.findByIdAndDeletedFalse(account.getOrganizationId());
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(organization), OrganizationExceptionEnum.ORGANIZATION_NOT_EXIST);
        String tradeNo = UUID.randomUUID().toString().replace("-", "");
        AddOrderDTO addOrder = new AddOrderDTO(tradeNo, membershipCard.getCardName(), membershipCard.getCardFee(), payPageInfo.getPhoneType());
        addOrder.setType(payPageInfo.getPhoneType());
        addOrder.setIpInfo(payPageInfo.getIpInfo());
        com.wechat.pay.java.service.payments.h5.model.PrepayResponse prepayResponse = wxPayService.addPageOrder(addOrder);
        log.info("创建h5订单返回结果: {}", GSON.toJson(prepayResponse));

        VipOrderDO order = new VipOrderDO();
        order.setVipId(payPageInfo.getMemberCardId());
        order.setVipName(membershipCard.getCardName());
        order.setOrganizationId(account.getOrganizationId());
        order.setTradeNo(tradeNo);
        order.setTotalPrice(membershipCard.getCardFee());
        order.setExpiresTime(new Timestamp(System.currentTimeMillis() + 2 * 60 * 60 * 1000));
        order.setPayState(PayState.TO_PAY);
        order.setOrgType(organization.getType());
        orderDao.save(order);
        VipOrderDetailDO detail = new VipOrderDetailDO();
        detail.setOrderId(order.getId());
        detail.setTradeNo(tradeNo);
        detail.setVipName(membershipCard.getCardName());
        detail.setTotalPrice(membershipCard.getCardFee());
        detail.setUnitPrice(membershipCard.getCardFee());
        detail.setOrgName(OrganizationType.ENTER.equals(organization.getType()) ? organization.getEnterName() : account.getUsername());
        detail.setUsername(account.getUsername());
        detail.setPhone(userInfo.getPhone());
        detail.setType("微信");
        detail.setOrgType(organization.getType());
        orderDetailDao.save(detail);
        return prepayResponse;
    }

    @Override
    public PageVO<OrderVO> getList(Long accountId, Pageable pageable) {
        Page<VipOrderDO> orderList = orderDao.findOrderByCreatorIdAndDeletedFalse(accountId, pageable);
        if (CollectionUtils.isEmpty(orderList.getContent())) {
            return new PageVO<>(0L, Collections.emptyList());
        }
        List<Long> orderIds = invoiceInfoDao.getOrderIds(orderList.stream().map(VipOrderDO::getId).collect(Collectors.toList()));

        return new PageVO<>(orderList.getTotalElements(), orderList.getContent().stream().map(data ->
                new OrderVO(data.getId(), data.getVipName(), data.getTradeNo(), data.getTotalPrice(), data.getPayTime(),
                        data.getPayState(), !CollectionUtils.isEmpty(orderIds) && orderIds.contains(data.getId()))
        ).collect(Collectors.toList()));
    }

    @Override
    public OrderDetailVO get(Long id) {
        VipOrderDO order = orderDao.findOrderByIdAndDeletedFalse(id);
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(order), OrderExceptionEnum.ORDER_NOT_EXIST);
        VipOrderDetailDO detail = orderDetailDao.findDetailByOrderIdAndDeletedFalse(id);
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(detail), OrderExceptionEnum.ORDER_DETAIL_NOT_EXIST);

        OrderDetailVO res = new OrderDetailVO();
        BeanUtils.copyProperties(detail, res);
        res.setPayState(order.getPayState());
        return res;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addInvoice(AddInvoiceForm form) {
        InvoiceInfoDO info = invoiceInfoDao.findInvoiceInfoByOrderIdAndDeletedFalse(form.getOrderId());
        AssertUtil.assertTrue(ObjectUtils.isEmpty(info), InvoiceExceptionEnum.INVOICE_EXIST);

        InvoiceInfoDO invoiceInfo = new InvoiceInfoDO();
        BeanUtils.copyProperties(form, invoiceInfo);
        invoiceInfo.setState(InvoiceState.INVOICING);
        invoiceInfoDao.save(invoiceInfo);
        return true;
    }

    @Override
    public PageVO<InvoiceVO> getInvoiceList(Long accountId, Pageable pageable) {
        Page<InvoiceInfoDO> page = invoiceInfoDao.findInvoiceInfoByCreatorIdAndDeletedFalse(accountId, pageable);
        if (CollectionUtils.isEmpty(page.getContent())) {
            return new PageVO<>(0L, Collections.emptyList());
        }

        Map<Long, Double> orders = orderDao.findOrderByIdInAndDeletedFalse(
                page.getContent().stream().map(InvoiceInfoDO::getOrderId).collect(Collectors.toList())
        ).stream().collect(Collectors.toMap(VipOrderDO::getId, VipOrderDO::getTotalPrice));

        return new PageVO<>(page.getTotalElements(), page.getContent().stream().map(data -> {
            InvoiceVO res = new InvoiceVO();
            res.setOrderId(data.getOrderId());
            res.setName(OrganizationType.ENTER.equals(data.getOrgType()) ? data.getEnterName() : data.getPersonName());
            res.setTotalPrice(orders.getOrDefault(data.getOrderId(), 0.0));
            res.setCreateTime(data.getCreateTime());
            res.setState(data.getState());
            return res;
        }).collect(Collectors.toList()));
    }

    @Override
    public PageVO<OrderPageVO> searchPage(SearchOrderForm form, Pageable pageable) {
        Page<VipOrderDO> page = orderDao.findOrderByTradeNoAndOrgType(form.getTradeNo(), OrganizationType.getValue(form.getType()),
                form.getOrderSource(), pageable);
        if (CollectionUtils.isEmpty(page.getContent())) {
            return new PageVO<>(0L, Collections.emptyList());
        }

        List<Long> orderIds = page.getContent().stream().map(VipOrderDO::getId).collect(Collectors.toList());
        Map<Long, InvoiceInfoDO> invoiceInfoMap = invoiceInfoDao.findInvoiceInfoByOrderIdInAndDeletedFalse(orderIds)
                .stream().collect(Collectors.toMap(InvoiceInfoDO::getOrderId, v -> v));

        return new PageVO<>(page.getTotalElements(), page.getContent().stream().map(data -> {
            OrderPageVO res = new OrderPageVO();
            res.setOrderId(data.getId());
            BeanUtils.copyProperties(data, res);
            if (data.getPrepayId() != null) {
                res.setOrderSource(1);
            } else {
                res.setOrderSource(2);
            }
            res.setIsInvoiced(invoiceInfoMap.containsKey(data.getId()));
            if (invoiceInfoMap.containsKey(data.getId())) {
                InvoiceDetailVO invoiceDetail = new InvoiceDetailVO();
                InvoiceInfoDO invoiceInfo = invoiceInfoMap.get(data.getId());
                BeanUtils.copyProperties(invoiceInfo, invoiceDetail);
                res.setInvoiceDetail(invoiceDetail);
            }
            return res;
        }).collect(Collectors.toList()));
    }

    @Override
    public Boolean modifyInvoice(Long id) {
        InvoiceInfoDO invoiceInfo = invoiceInfoDao.findInvoiceInfoByIdAndDeletedFalse(id);
        if (!ObjectUtils.isEmpty(invoiceInfo)) {
            invoiceInfo.setState(InvoiceState.INVOICED);
            invoiceInfoDao.save(invoiceInfo);
        }
        return true;
    }

    @Override
    public String addByAlipay(Long accountId, AddOrderForm form) {
        VipInfoDO vipInfo = vipInfoDao.findByIdAndDeletedFalse(form.getVipId());
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(vipInfo), VipExceptionEnum.VIP_NOT_EXIST);
        AccountDO account = accountDao.findByIdAndDeletedFalse(accountId);
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(account), AccountExceptionEnum.ACCOUNT_NOT_EXIST);
        UserInfoDO userInfo = userInfoDao.findByIdAndDeletedFalse(account.getUserId());
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(userInfo), UserExceptionEnum.USER_NOT_EXIST);
        OrganizationDO organization = organizationDao.findByIdAndDeletedFalse(account.getOrganizationId());
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(organization), OrganizationExceptionEnum.ORGANIZATION_NOT_EXIST);

        inviteCodeService.bindInviteRecord(form.getCode(), organization.getId(), accountId);

        String tradeNo = UUID.randomUUID().toString().replace("-", "");
        String response = appAliPayService.addOrder(new AddOrderDTO(tradeNo, vipInfo.getName(), vipInfo.getTotalPrice(), userInfo.getOpenId()));

        VipOrderDO order = new VipOrderDO();
        order.setVipId(form.getVipId());
        order.setVipName(vipInfo.getName());
        order.setOrganizationId(account.getOrganizationId());
        order.setTradeNo(tradeNo);
        order.setTotalPrice(vipInfo.getTotalPrice());
        order.setExpiresTime(new Timestamp(System.currentTimeMillis() + 2 * 60 * 60 * 1000));
        order.setPayState(PayState.TO_PAY);
        order.setOrgType(organization.getType());
        orderDao.save(order);
        VipOrderDetailDO detail = new VipOrderDetailDO();
        detail.setOrderId(order.getId());
        detail.setTradeNo(tradeNo);
        detail.setVipName(vipInfo.getName());
        detail.setTotalPrice(vipInfo.getTotalPrice());
        detail.setUnitPrice(vipInfo.getUnitPrice());
        detail.setDuration(vipInfo.getDuration());
        detail.setQueryTotalNum(vipInfo.getQueryTotalNum());
        detail.setAccountNum(vipInfo.getAccountNum());
        detail.setOrgName(OrganizationType.ENTER.equals(organization.getType()) ? organization.getEnterName() : account.getUsername());
        detail.setUsername(account.getUsername());
        detail.setPhone(userInfo.getPhone());
        detail.setType("支付宝");
        detail.setOrgType(organization.getType());
        orderDetailDao.save(detail);
        log.info("创建APP支付宝支付订单号: {}, 订单参数：{}", tradeNo, response);
        return response;
    }

    @Override
    public String callOrderByAlipay(HttpServletRequest request) {
        LinkedHashMap<String, String> params = appAliPayService.callOrder(request);
        if (CollectionUtils.isEmpty(params)) {
            return "fail";
        }

        String outTradeNo = params.get("out_trade_no");
        String tradeStatus = params.get("trade_status");
        if (StringUtils.isBlank(outTradeNo) || StringUtils.isBlank(tradeStatus)) {
            return "fail";
        }

        //保存交易信息
        VipOrderNotifyDO notify = new VipOrderNotifyDO();
        notify.setTradeNo(outTradeNo);
        notify.setResult(GSON.toJson(params));
        orderNotifyDao.save(notify);

        VipOrderDO order = orderDao.findOrderByTradeNoAndDeletedFalse(outTradeNo);
        if (ObjectUtils.isEmpty(order)) {
            log.info("订单号: {} 对应订单不存在", outTradeNo);
            return "fail";
        }
        VipOrderDetailDO detail = orderDetailDao.findDetailByOrderIdAndDeletedFalse(order.getId());
        if (ObjectUtils.isEmpty(detail)) {
            log.info("订单 id : {}, 订单号: {} 详情不存在", order.getId(), order.getTradeNo());
            return "fail";
        }
        if (PayState.SUCCESS.equals(order.getPayState())) {
            log.info("订单号: {} 已支付", outTradeNo);
            return "success";
        }
        if (StringUtils.isNotBlank(outTradeNo) && StringUtils.isNotBlank(tradeStatus)) {
            String payTimeStr = params.get("gmt_payment");
            Timestamp payTime = TimeUtil.transferTime(payTimeStr, Regulation.WHOLE_TIME);
            order.setPayTime(payTime);
            order.setState(tradeStatus);
            order.setPayState(PayState.SUCCESS);
            orderDao.save(order);

            detail.setPayTime(payTime);
            detail.setEffectiveTime(payTime);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(Regulation.WHOLE_TIME);
            LocalDateTime dateTime = LocalDateTime.parse(payTimeStr, formatter);
            detail.setExpiresTime(ObjectUtils.isEmpty(detail.getDuration()) ? null : Timestamp.valueOf(dateTime.plus(detail.getDuration(), ChronoUnit.YEARS)));
            orderDetailDao.save(detail);



            OrgVipRecordDO orgVipRecord = orgVipRecordDao.findRecordByOrganizationIdAndDeletedFalse(order.getOrganizationId());
            if (ObjectUtils.isEmpty(orgVipRecord)) {
                orgVipRecord = new OrgVipRecordDO();
                orgVipRecord.setOrganizationId(order.getOrganizationId());
                orgVipRecord.setTotalSearchTimes(detail.getQueryTotalNum());
                orgVipRecord.setAccountNum(detail.getAccountNum());
                orgVipRecord.setExpiresTime(detail.getExpiresTime());
                orgVipRecord.setBuySearchTimes(detail.getQueryTotalNum());
                orgVipRecordDao.save(orgVipRecord);
            } else {
                orgVipRecord.setTotalSearchTimes(orgVipRecord.getTotalSearchTimes() + detail.getQueryTotalNum());
                orgVipRecord.setBuySearchTimes((orgVipRecord.getBuySearchTimes() == null ? 0 : orgVipRecord.getBuySearchTimes()) + detail.getQueryTotalNum());
                if (!ObjectUtils.isEmpty(detail.getDuration())) {
                    Calendar c = Calendar.getInstance();
                    c.setTime(ObjectUtils.isEmpty(orgVipRecord.getExpiresTime()) ? new Timestamp(System.currentTimeMillis()) : orgVipRecord.getExpiresTime());
                    c.add(Calendar.YEAR, detail.getDuration());
                    orgVipRecord.setExpiresTime(new Timestamp(c.getTimeInMillis()));
                }
                if (orgVipRecord.getAccountNum() == null || (!ObjectUtils.isEmpty(detail.getAccountNum()) && orgVipRecord.getAccountNum() < detail.getAccountNum())) {
                    orgVipRecord.setAccountNum(detail.getAccountNum());
                }
                orgVipRecordDao.save(orgVipRecord);
            }

            return "success";
        } else {
            String payTimeStr = params.get("gmt_payment");
            Timestamp payTime = TimeUtil.transferTime(payTimeStr, Regulation.WHOLE_TIME);

            order.setPayTime(payTime);
            order.setState(tradeStatus);
            order.setPayState(PayState.FAILURE);
            orderDao.save(order);

            detail.setPayTime(payTime);
            orderDetailDao.save(detail);

            return "fail";
        }
    }

    @Override
    public String addByAlipayWap(Long accountId, Long memberCardId) {
        MembershipCardDO vipInfo = membershipCardDao.findInfoByIdAndIsDeletedFalse(memberCardId);
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(vipInfo), VipExceptionEnum.VIP_NOT_EXIST);
        AccountDO account = accountDao.findByIdAndDeletedFalse(accountId);
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(account), AccountExceptionEnum.ACCOUNT_NOT_EXIST);
        UserInfoDO userInfo = userInfoDao.findByIdAndDeletedFalse(account.getUserId());
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(userInfo), UserExceptionEnum.USER_NOT_EXIST);
        OrganizationDO organization = organizationDao.findByIdAndDeletedFalse(account.getOrganizationId());
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(organization), OrganizationExceptionEnum.ORGANIZATION_NOT_EXIST);

        //inviteCodeService.bindInviteRecord(form.getCode(), organization.getId(), accountId);

        String tradeNo = UUID.randomUUID().toString().replace("-", "");
        AddOrderDTO addOrder = new AddOrderDTO(tradeNo, vipInfo.getCardName(), vipInfo.getCardFee());
        addOrder.setType(vipInfo.getId() == 2 ? ShareType.NORMAL.getValue() : ShareType.HIGH.getValue());
        String response = wapAliPayService.addOrder(addOrder);
        VipOrderDO order = new VipOrderDO();
        order.setVipId(vipInfo.getId());
        order.setVipName(vipInfo.getCardName());
        order.setOrganizationId(account.getOrganizationId());
        order.setTradeNo(tradeNo);
        order.setTotalPrice(vipInfo.getCardFee());
        order.setExpiresTime(new Timestamp(System.currentTimeMillis() + 2 * 60 * 60 * 1000));
        order.setPayState(PayState.TO_PAY);
        order.setOrgType(organization.getType());
        orderDao.save(order);
        VipOrderDetailDO detail = new VipOrderDetailDO();
        detail.setOrderId(order.getId());
        detail.setTradeNo(tradeNo);
        detail.setVipName(vipInfo.getCardName());
        detail.setTotalPrice(vipInfo.getCardFee());
        detail.setUnitPrice(vipInfo.getCardFee());
//        detail.setDuration(vipInfo.getDuration());
//        detail.setQueryTotalNum(vipInfo.getQueryTotalNum());
//        detail.setAccountNum(vipInfo.getAccountNum());
        detail.setOrgName(OrganizationType.ENTER.equals(organization.getType()) ? organization.getEnterName() : account.getUsername());
        detail.setUsername(account.getUsername());
        detail.setPhone(userInfo.getPhone());
        detail.setType("支付宝");
        detail.setOrgType(organization.getType());
        orderDetailDao.save(detail);
        log.info("创建h5支付宝支付订单号: {}, 订单参数：{}", tradeNo, response);
        return response;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String callOrderByAlipayWap(HttpServletRequest request) {
        LinkedHashMap<String, String> params = wapAliPayService.callOrder(request);
        if (CollectionUtils.isEmpty(params)) {
            return "fail";
        }

        String outTradeNo = params.get("out_trade_no");
        String tradeStatus = params.get("trade_status");
        if (StringUtils.isBlank(outTradeNo) || StringUtils.isBlank(tradeStatus)) {
            return "fail";
        }

        //保存交易信息
        VipOrderNotifyDO notify = new VipOrderNotifyDO();
        notify.setTradeNo(outTradeNo);
        notify.setResult(GSON.toJson(params));
        orderNotifyDao.save(notify);

        VipOrderDO order = orderDao.findOrderByTradeNoAndDeletedFalse(outTradeNo);
        if (ObjectUtils.isEmpty(order)) {
            log.info("订单号: {} 对应订单不存在", outTradeNo);
            return "fail";
        }
        VipOrderDetailDO detail = orderDetailDao.findDetailByOrderIdAndDeletedFalse(order.getId());
        if (ObjectUtils.isEmpty(detail)) {
            log.info("订单 id : {}, 订单号: {} 详情不存在", order.getId(), order.getTradeNo());
            return "fail";
        }

        if (PayState.SUCCESS.equals(order.getPayState())) {
            log.info("订单号: {} 已支付", outTradeNo);
            return "success";
        }

        if (StringUtils.isNotBlank(outTradeNo) && StringUtils.isNotBlank(tradeStatus)) {
            String payTimeStr = params.get("gmt_payment");
            Timestamp payTime = TimeUtil.transferTime(payTimeStr, Regulation.WHOLE_TIME);
            order.setPayTime(payTime);
            order.setState(tradeStatus);
            order.setPayState(PayState.SUCCESS);
            order.setHistoryScore(Double.valueOf(String.format("%.2f", order.getTotalPrice() * 0.4)));
            Double superHistoryScore = Double.valueOf(String.format("%.2f", order.getTotalPrice() * 0.1));
            orderDao.save(order);

            detail.setPayTime(payTime);
            detail.setEffectiveTime(payTime);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(Regulation.WHOLE_TIME);
            LocalDateTime dateTime = LocalDateTime.parse(payTimeStr, formatter);
            detail.setExpiresTime(ObjectUtils.isEmpty(detail.getDuration()) ? null : Timestamp.valueOf(dateTime.plus(detail.getDuration(), ChronoUnit.YEARS)));
            orderDetailDao.save(detail);

//            OrgVipRecordDO orgVipRecord = orgVipRecordDao.findRecordByOrganizationIdAndDeletedFalse(order.getOrganizationId());
//            if (ObjectUtils.isEmpty(orgVipRecord)) {
//                orgVipRecord = new OrgVipRecordDO();
//                orgVipRecord.setOrganizationId(order.getOrganizationId());
//                orgVipRecord.setTotalSearchTimes(detail.getQueryTotalNum());
//                orgVipRecord.setAccountNum(detail.getAccountNum());
//                orgVipRecord.setExpiresTime(detail.getExpiresTime());
//                orgVipRecord.setBuySearchTimes(detail.getQueryTotalNum());
//                orgVipRecordDao.save(orgVipRecord);
//            } else {
//                orgVipRecord.setTotalSearchTimes(orgVipRecord.getTotalSearchTimes() + detail.getQueryTotalNum());
//                orgVipRecord.setBuySearchTimes((orgVipRecord.getBuySearchTimes() == null ? 0 : orgVipRecord.getBuySearchTimes()) + detail.getQueryTotalNum());
//                if (!ObjectUtils.isEmpty(detail.getDuration())) {
//                    Calendar c = Calendar.getInstance();
//                    c.setTime(ObjectUtils.isEmpty(orgVipRecord.getExpiresTime()) ? new Timestamp(System.currentTimeMillis()) : orgVipRecord.getExpiresTime());
//                    c.add(Calendar.YEAR, detail.getDuration());
//                    orgVipRecord.setExpiresTime(new Timestamp(c.getTimeInMillis()));
//                }
//                if (orgVipRecord.getAccountNum() == null || (!ObjectUtils.isEmpty(detail.getAccountNum()) && orgVipRecord.getAccountNum() < detail.getAccountNum())) {
//                    orgVipRecord.setAccountNum(detail.getAccountNum());
//                }
//                orgVipRecordDao.save(orgVipRecord);
//            }
            //增加查询次数
            AccountDO accountInformation = accountDao.findByIdAndDeletedFalse(order.getCreatorId());
            Long organizationId = accountInformation.getOrganizationId();
            OrgVipRecordDO orgVipRecord = orgVipRecordDao.findRecordByOrganizationIdAndDeletedFalse(organizationId);
            int totalSearchTimes = order.getVipId() == 2 ? 10 : 100;
            if (ObjectUtils.isEmpty(orgVipRecord)) {
                orgVipRecord = new OrgVipRecordDO();
                orgVipRecord.setOrganizationId(order.getOrganizationId());
                orgVipRecord.setTotalSearchTimes(totalSearchTimes);
                orgVipRecord.setAccountNum(detail.getAccountNum());
                orgVipRecord.setExpiresTime(detail.getExpiresTime());
                orgVipRecord.setBuySearchTimes(totalSearchTimes);
                orgVipRecordDao.save(orgVipRecord);
            } else {
                orgVipRecord.setTotalSearchTimes(orgVipRecord.getTotalSearchTimes() + totalSearchTimes);
                orgVipRecord.setBuySearchTimes((orgVipRecord.getBuySearchTimes() == null ? 0 : orgVipRecord.getBuySearchTimes()) + totalSearchTimes);
                orgVipRecordDao.save(orgVipRecord);
            }

            List<InviteRecordDO> existInviteRecords = inviteRecordDao.findRecordByCreatorIdAndTypeAndDeletedFalse(order.getCreatorId(), InviteCodeType.INVITE);
            if (!CollectionUtils.isEmpty(existInviteRecords)) {
                existInviteRecords.sort(Comparator.comparing(InviteRecordDO::getId, Comparator.reverseOrder()));
                InviteRecordDO inviteRecord = existInviteRecords.get(0);
                inviteRecord.setIsPay(true);
                inviteRecord.setShareType(order.getVipId() == 2 ? ShareType.NORMAL.getValue() : ShareType.HIGH.getValue());
                inviteRecordDao.save(inviteRecord);
                String inviteCode = inviteRecord.getInviteCode();
                Long operatorId = inviteCodeDao.findCodeByInviteCodeAndDeletedFalse(inviteCode).getOperatorId();
                AccountDO account = accountDao.findByIdAndDeletedFalse(operatorId);
                Double historyScore = account.getHistoryScore();
                account.setHistoryScore(historyScore == null ? order.getHistoryScore() : historyScore + order.getHistoryScore());
                accountDao.save(account);
                // 给分享上级积分
                List<InviteRecordDO> recordInfos = inviteRecordDao.findRecordByCreatorIdAndTypeAndDeletedFalse(operatorId, InviteCodeType.INVITE);
                if (!CollectionUtils.isEmpty(recordInfos)) {
                    String inviteCodeInfo = recordInfos.get(0).getInviteCode();
                    InviteCodeDO codeInfo = inviteCodeDao.findCodeByInviteCodeAndDeletedFalse(inviteCodeInfo);
                    Long operator = codeInfo.getOperatorId();
                    AccountDO accountInfo = accountDao.findByIdAndDeletedFalse(operator);
                    Double historyScoreInfo = accountInfo.getHistoryScore();
                    accountInfo.setHistoryScore(historyScoreInfo == null ? superHistoryScore : historyScoreInfo + superHistoryScore);
                    accountDao.save(accountInfo);
                }
            }
            return "success";
        } else {
            String payTimeStr = params.get("gmt_payment");
            Timestamp payTime = TimeUtil.transferTime(payTimeStr, Regulation.WHOLE_TIME);

            order.setPayTime(payTime);
            order.setState(tradeStatus);
            order.setPayState(PayState.FAILURE);
            orderDao.save(order);

            detail.setPayTime(payTime);
            orderDetailDao.save(detail);

            return "fail";
        }
    }

    @Override
    public String addByAlipayTimeWap(Long accountId, Long memberCardId, Long monitorRecordId) {
        MembershipCardDO vipInfo = membershipCardDao.findInfoByIdAndIsDeletedFalse(memberCardId);
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(vipInfo), VipExceptionEnum.VIP_NOT_EXIST);
        AccountDO account = accountDao.findByIdAndDeletedFalse(accountId);
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(account), AccountExceptionEnum.ACCOUNT_NOT_EXIST);
        UserInfoDO userInfo = userInfoDao.findByIdAndDeletedFalse(account.getUserId());
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(userInfo), UserExceptionEnum.USER_NOT_EXIST);
        OrganizationDO organization = organizationDao.findByIdAndDeletedFalse(account.getOrganizationId());
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(organization), OrganizationExceptionEnum.ORGANIZATION_NOT_EXIST);

        String tradeNo = UUID.randomUUID().toString().replace("-", "");
        AddOrderDTO addOrder = new AddOrderDTO(tradeNo, vipInfo.getCardName(), vipInfo.getCardFee());
        String response = wapAliPayService.addTimeOrder(addOrder);
        VipOrderDO order = new VipOrderDO();
        order.setVipId(vipInfo.getId());
        order.setVipName(vipInfo.getCardName());
        order.setOrganizationId(account.getOrganizationId());
        order.setTradeNo(tradeNo);
        order.setTotalPrice(vipInfo.getCardFee());
        order.setExpiresTime(new Timestamp(System.currentTimeMillis() + 2 * 60 * 60 * 1000));
        order.setPayState(PayState.TO_PAY);
        order.setOrgType(organization.getType());
        orderDao.save(order);
        VipOrderDetailDO detail = new VipOrderDetailDO();
        detail.setOrderId(order.getId());
        detail.setTradeNo(tradeNo);
        detail.setVipName(vipInfo.getCardName());
        detail.setTotalPrice(vipInfo.getCardFee());
        detail.setUnitPrice(vipInfo.getCardFee());
        detail.setOrgName(OrganizationType.ENTER.equals(organization.getType()) ? organization.getEnterName() : account.getUsername());
        detail.setUsername(account.getUsername());
        detail.setPhone(userInfo.getPhone());
        detail.setType("支付宝");
        detail.setOrgType(organization.getType());
        orderDetailDao.save(detail);
        MonitorRecordDO monitorRecord = monitorRecordDao.findInfoByIdAndDisabledFalse(monitorRecordId);
        monitorRecord.setOrderId(order.getId());
        monitorRecord.setIsPay(false);
        monitorRecordDao.save(monitorRecord);
        log.info("创建定时监控h5支付宝支付订单号: {}, 订单参数：{}", tradeNo, response);
        return response;
    }

    @Override
    public String callTimeOrderByAlipayWap(HttpServletRequest request) {
        LinkedHashMap<String, String> params = wapAliPayService.callOrder(request);
        if (CollectionUtils.isEmpty(params)) {
            return "fail";
        }

        String outTradeNo = params.get("out_trade_no");
        String tradeStatus = params.get("trade_status");
        if (StringUtils.isBlank(outTradeNo) || StringUtils.isBlank(tradeStatus)) {
            return "fail";
        }

        //保存交易信息
        VipOrderNotifyDO notify = new VipOrderNotifyDO();
        notify.setTradeNo(outTradeNo);
        notify.setResult(GSON.toJson(params));
        orderNotifyDao.save(notify);

        VipOrderDO order = orderDao.findOrderByTradeNoAndDeletedFalse(outTradeNo);
        if (ObjectUtils.isEmpty(order)) {
            log.info("订单号: {} 对应订单不存在", outTradeNo);
            return "fail";
        }
        VipOrderDetailDO detail = orderDetailDao.findDetailByOrderIdAndDeletedFalse(order.getId());
        if (ObjectUtils.isEmpty(detail)) {
            log.info("订单 id : {}, 订单号: {} 详情不存在", order.getId(), order.getTradeNo());
            return "fail";
        }

        if (PayState.SUCCESS.equals(order.getPayState())) {
            log.info("订单号: {} 已支付", outTradeNo);
            return "success";
        }

        if (StringUtils.isNotBlank(outTradeNo) && StringUtils.isNotBlank(tradeStatus)) {
            String payTimeStr = params.get("gmt_payment");
            Timestamp payTime = TimeUtil.transferTime(payTimeStr, Regulation.WHOLE_TIME);
            order.setPayTime(payTime);
            order.setState(tradeStatus);
            order.setPayState(PayState.SUCCESS);
            orderDao.save(order);

            detail.setPayTime(payTime);
            detail.setEffectiveTime(payTime);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(Regulation.WHOLE_TIME);
            LocalDateTime dateTime = LocalDateTime.parse(payTimeStr, formatter);
            detail.setExpiresTime(ObjectUtils.isEmpty(detail.getDuration()) ? null : Timestamp.valueOf(dateTime.plus(detail.getDuration(), ChronoUnit.YEARS)));
            orderDetailDao.save(detail);
            Long creatorId = order.getCreatorId();
            // 支付成功发短信并调用外部接口添加监控信息
            Date now = new Date();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());  // 设置当前日期
            calendar.add(Calendar.MONTH, 3);  // 加上三个月
            Date threeMonthsLater = calendar.getTime();
            MonitorRecordDO monitorRecord = monitorRecordDao.findInfoByOrderIdAndDisabledFalse(order.getId());
            monitorRecord.setExpireTime(threeMonthsLater);
            monitorRecord.setIsPay(true);
            monitorRecordDao.save(monitorRecord);
            MonitorEntityDO monitorEntity = monitorEntityDao.findInfoByMonitorContentAndMonitorType(monitorRecord.getMonitorContent(),
                    monitorRecord.getMonitorType());
            if (monitorEntity == null) {
                monitorEntity = new MonitorEntityDO();
                monitorEntity.setMonitorContent(monitorRecord.getMonitorContent());
                monitorEntity.setMonitorType(monitorRecord.getMonitorType());
                monitorEntity.setCreateTime(now);
                monitorEntityDao.save(monitorEntity);
            }
            try {
                MonitorPersonAddDTO monitorPersonAdd = JSON.parseObject(monitorRecord.getMonitorContent(), MonitorPersonAddDTO.class);
                if (MonitorType.PERSON.getValue().equals(monitorRecord.getMonitorType())) {
                    openApiService.personAddMonitorProd(monitorPersonAdd);
                }
                if (MonitorType.ENTER.getValue().equals(monitorRecord.getMonitorType())) {
                    openApiService.enterAddMonitorProd(new MonitorEnterAddDTO(monitorPersonAdd.getName()));
                }
            } catch (Exception e) {
                log.info("添加外部监控信息失败，监控内容：{}, 监控人accountId：{}", monitorRecord.getMonitorContent(), creatorId, e);
            }
            List<MonitorRecordDO> paySuccessMonitorRecord = monitorRecordDao.findInfosByCreatorIdAndIsPayTrueAndDisabledFalse(creatorId);
            paySuccessMonitorRecord = paySuccessMonitorRecord.stream().filter(s -> now.before(s.getExpireTime()) ||
                    now.equals(s.getExpireTime())).collect(Collectors.toList());
            SendTimerAuthDataDTO sendTimerAuthData = new SendTimerAuthDataDTO();
            String monitorContent = monitorRecord.getMonitorContent();
            MonitorPersonAddDTO monitorPersonAdd = JSON.parseObject(monitorContent, MonitorPersonAddDTO.class);
            sendTimerAuthData.setTarget(monitorPersonAdd.getName());
            List<String> contentArr = new ArrayList<>();
            int personSum = 0;
            int enterSum = 0;
            for (MonitorRecordDO monitor : paySuccessMonitorRecord) {
                Integer monitorType = monitor.getMonitorType();
                if (MonitorType.PERSON.getValue().equals(monitorType)) {
                    personSum++;
                }
                if (MonitorType.ENTER.getValue().equals(monitorType)) {
                    enterSum++;
                }
            }
            if (enterSum != 0) {
                contentArr.add(enterSum + "家企业");
            }
            if (personSum != 0) {
                contentArr.add(personSum + "个个人");
            }
            sendTimerAuthData.setContent(String.join(",", contentArr));
            try {
                smsService.sendTimerMsgCode(detail.getPhone(), sendTimerAuthData, null, SmsTemplateType.TIMER_AUTH);
            } catch (Exception e) {
                log.info("发送定时监控通知短信失败，监控内容：{}, 监控人accountId: {}", monitorContent, creatorId, e);
            }
            return "success";
        } else {
            String payTimeStr = params.get("gmt_payment");
            Timestamp payTime = TimeUtil.transferTime(payTimeStr, Regulation.WHOLE_TIME);

            order.setPayTime(payTime);
            order.setState(tradeStatus);
            order.setPayState(PayState.FAILURE);
            orderDao.save(order);

            detail.setPayTime(payTime);
            orderDetailDao.save(detail);

            return "fail";
        }
    }

    @Override
    public AddAlipayAppletVO addByAlipayApplet(Long accountId, AddOrderByAlipayAppletForm form) {
        VipInfoDO vipInfo = vipInfoDao.findByTypeAndDeletedFalse(OrganizationType.ALIPAY).stream().max(Comparator.comparing(VipInfoDO::getId)).orElse(null);
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(vipInfo), VipExceptionEnum.VIP_NOT_EXIST);
        AccountDO account = accountDao.findByIdAndDeletedFalse(accountId);
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(account), AccountExceptionEnum.ACCOUNT_NOT_EXIST);
        UserInfoDO userInfo = userInfoDao.findByIdAndDeletedFalse(account.getUserId());
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(userInfo), UserExceptionEnum.USER_NOT_EXIST);
        OrganizationDO organization = organizationDao.findByIdAndDeletedFalse(account.getOrganizationId());
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(organization), OrganizationExceptionEnum.ORGANIZATION_NOT_EXIST);

        DiscountCodeDO discountCodeInfo = null;
        if (StringUtils.isNotBlank(form.getDiscountCode())) {
            discountCodeInfo = discountCodeDao.findDiscountCodeByDiscountCodeAndDeletedFalse(form.getDiscountCode());
        }
        Double payPrice;
        List<MembershipCardAccountDO> existMembershipCardAccountInfos = membershipCardAccountDao.findInfosByAccountId(accountId);
        if (!CollectionUtils.isEmpty(existMembershipCardAccountInfos)) {
            Date now = new Date();
            existMembershipCardAccountInfos = existMembershipCardAccountInfos.stream().filter(s -> s.getExpireTime().after(now)
                    || s.getExpireTime().equals(now)).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(existMembershipCardAccountInfos)) {
                MembershipCardAccountDO membershipCardAccount = existMembershipCardAccountInfos.stream()
                        .max(Comparator.comparingDouble(MembershipCardAccountDO::getDiscountFee)).get();
                payPrice = membershipCardAccount.getDiscountFee();
            } else {
                payPrice = vipInfo.getTotalPrice();
            }
        } else {
            if (discountCodeInfo != null && discountCodeInfo.getIsValid()) {
                int existUseTimes = orderDao.findOrderInfosByDiscountCodeIdInAndPayStateAndDeletedFalse(Collections.
                        singletonList(discountCodeInfo.getId()), PayState.SUCCESS).size();
                if (discountCodeInfo.getUseTimes() == null || existUseTimes <= discountCodeInfo.getUseTimes()) {
                    BigDecimal discountPrice = BigDecimal.valueOf(discountCodeInfo.getDiscountPrice());
                    BigDecimal totalPrice = BigDecimal.valueOf(vipInfo.getTotalPrice());
                    BigDecimal subtract = totalPrice.subtract(discountPrice).setScale(2, RoundingMode.HALF_UP);
                    AssertUtil.assertTrue(subtract.doubleValue() > 0.0, DisCountCodeExceptionEnum.DISCOUNT_PRICE_ERROR);
                    payPrice = subtract.doubleValue();
                } else {
                    payPrice = vipInfo.getTotalPrice();
                }
            } else {
                payPrice = vipInfo.getTotalPrice();
            }
        }

        // 获取会员信息 userid
        String aliAppletUserId = aliAppletService.getUserId(accountId, form.getAuthCode());
        AssertUtil.assertTrue(StringUtils.isNotBlank(aliAppletUserId), SysCode.ALI_APPLET_API_GET_USERID_ERROR);

        String tradeNo = UUID.randomUUID().toString().replace("-", "");
        AlipayTradeCreateResponse response = aliAppletService.addOrder(accountId, new AddOrderDTO(tradeNo, vipInfo.getName(), payPrice, aliAppletUserId));
        AssertUtil.assertTrue((response != null), SysCode.ALI_APPLET_API_ADD_ORDER_ERROR);

        VipOrderDO order = new VipOrderDO();
        order.setVipId(vipInfo.getId());
        order.setVipName(vipInfo.getName());
        order.setOrganizationId(account.getOrganizationId());
        order.setTradeNo(tradeNo);
        order.setTotalPrice(payPrice);
        order.setExpiresTime(new Timestamp(System.currentTimeMillis() + 2 * 60 * 60 * 1000));
        order.setPayState(PayState.TO_PAY);
        order.setOrgType(organization.getType());
        if (discountCodeInfo != null) {
            order.setDiscountCodeId(discountCodeInfo.getId());
        }
        orderDao.save(order);
        VipOrderDetailDO detail = new VipOrderDetailDO();
        detail.setOrderId(order.getId());
        detail.setTradeNo(tradeNo);
        detail.setVipName(vipInfo.getName());
        detail.setTotalPrice(payPrice);
        detail.setUnitPrice(vipInfo.getUnitPrice());
        detail.setDuration(vipInfo.getDuration());
        detail.setQueryTotalNum(vipInfo.getQueryTotalNum());
        detail.setAccountNum(vipInfo.getAccountNum());
        detail.setOrgName(OrganizationType.ENTER.equals(organization.getType()) ? organization.getEnterName() : account.getUsername());
        detail.setUsername(account.getUsername());
        detail.setPhone(userInfo.getPhone());
        detail.setType("支付宝小程序");
        detail.setOrgType(organization.getType());
        orderDetailDao.save(detail);

        if (form.getQueryId() != null) {
            QueryRecordDO queryRecord = queryRecordDao.findByIdAndDeletedFalse(form.getQueryId());
            if (queryRecord != null) {
                queryRecord.setTradeNo(tradeNo);
                queryRecordDao.save(queryRecord);
            }
        }
        return new AddAlipayAppletVO(response.getOutTradeNo(), response.getTradeNo());
    }

    @Override
    public AddAlipayAppletVO addByAlipayAppletMembershipCard(Long accountId, AddOrderForMembershipCardForm form) {

        MembershipCardDO membershipCard = membershipCardDao.findInfoByIdAndIsDeletedFalse(form.getMembershipCardId());
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(membershipCard), VipExceptionEnum.VIP_NOT_EXIST);
        AccountDO account = accountDao.findByIdAndDeletedFalse(accountId);
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(account), AccountExceptionEnum.ACCOUNT_NOT_EXIST);
        UserInfoDO userInfo = userInfoDao.findByIdAndDeletedFalse(account.getUserId());
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(userInfo), UserExceptionEnum.USER_NOT_EXIST);
        OrganizationDO organization = organizationDao.findByIdAndDeletedFalse(account.getOrganizationId());
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(organization), OrganizationExceptionEnum.ORGANIZATION_NOT_EXIST);

        // 获取会员信息 userid
        String aliAppletUserId = aliAppletService.getUserId(accountId, form.getAuthCode());
        AssertUtil.assertTrue(StringUtils.isNotBlank(aliAppletUserId), SysCode.ALI_APPLET_API_GET_USERID_ERROR);

        String tradeNo = UUID.randomUUID().toString().replace("-", "");
        AlipayTradeCreateResponse response = aliAppletService.addOrderForMembershipCard(accountId, new AddOrderDTO(tradeNo, membershipCard.getCardName(),
                membershipCard.getCardFee(), aliAppletUserId));
        AssertUtil.assertTrue((response != null), SysCode.ALI_APPLET_API_ADD_ORDER_ERROR);

        VipOrderDO order = new VipOrderDO();
        order.setVipId(membershipCard.getId());
        order.setVipName(membershipCard.getCardName());
        order.setOrganizationId(account.getOrganizationId());
        order.setTradeNo(tradeNo);
        order.setTotalPrice(membershipCard.getCardFee());
        order.setExpiresTime(new Timestamp(System.currentTimeMillis() + 2 * 60 * 60 * 1000));
        order.setPayState(PayState.TO_PAY);
        order.setOrgType(organization.getType());

        orderDao.save(order);
        VipOrderDetailDO detail = new VipOrderDetailDO();
        detail.setOrderId(order.getId());
        detail.setTradeNo(tradeNo);
        detail.setVipName(membershipCard.getCardName());
        detail.setTotalPrice(membershipCard.getCardFee());
        detail.setUnitPrice(membershipCard.getCardFee());
        detail.setDuration(membershipCard.getValidDays());
        detail.setOrgName(OrganizationType.ENTER.equals(organization.getType()) ? organization.getEnterName() : account.getUsername());
        detail.setUsername(account.getUsername());
        detail.setPhone(userInfo.getPhone());
        detail.setType("支付宝小程序");
        detail.setOrgType(organization.getType());
        orderDetailDao.save(detail);
        return new AddAlipayAppletVO(response.getOutTradeNo(), response.getTradeNo());
    }

    @Override
    public String callOrderByAlipayApplet(HttpServletRequest request) {
        LinkedHashMap<String, String> params = aliAppletService.callOrder(request);
        if (CollectionUtils.isEmpty(params)) {
            return "fail";
        }

        String outTradeNo = params.get("out_trade_no");
        String tradeStatus = params.get("trade_status");
        if (StringUtils.isBlank(outTradeNo) || StringUtils.isBlank(tradeStatus)) {
            return "fail";
        }

        //保存交易信息
        VipOrderNotifyDO notify = new VipOrderNotifyDO();
        notify.setTradeNo(outTradeNo);
        notify.setResult(GSON.toJson(params));
        orderNotifyDao.save(notify);

        VipOrderDO order = orderDao.findOrderByTradeNoAndDeletedFalse(outTradeNo);
        if (ObjectUtils.isEmpty(order)) {
            log.info("订单号: {} 对应订单不存在", outTradeNo);
            return "fail";
        }
        VipOrderDetailDO detail = orderDetailDao.findDetailByOrderIdAndDeletedFalse(order.getId());
        if (ObjectUtils.isEmpty(detail)) {
            log.info("订单 id : {}, 订单号: {} 详情不存在", order.getId(), order.getTradeNo());
            return "fail";
        }

        if (PayState.SUCCESS.equals(order.getPayState())) {
            log.info("订单号: {} 已支付", outTradeNo);
            return "success";
        }

        if (StringUtils.isNotBlank(outTradeNo) && StringUtils.isNotBlank(tradeStatus)) {
            String payTimeStr = params.get("gmt_payment");
            Timestamp payTime = TimeUtil.transferTime(payTimeStr, Regulation.WHOLE_TIME);
            order.setPayTime(payTime);
            order.setState(tradeStatus);
            order.setPayState(PayState.SUCCESS);
            orderDao.save(order);

            detail.setPayTime(payTime);
            detail.setEffectiveTime(payTime);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(Regulation.WHOLE_TIME);
            LocalDateTime dateTime = LocalDateTime.parse(payTimeStr, formatter);
            detail.setExpiresTime(ObjectUtils.isEmpty(detail.getDuration()) ? null : Timestamp.valueOf(dateTime.plus(detail.getDuration(), ChronoUnit.YEARS)));
            orderDetailDao.save(detail);

            QueryRecordDO queryRecord = queryRecordDao.findByTradeNoAndDeletedFalse(outTradeNo);
            if (queryRecord != null && SearchType.ENTERPRISE.equals(queryRecord.getType())) {
                queryRecord.setAuthorizedResult(AuthResultType.AUTHORIZED);
                queryRecord.setShow(true);
                queryRecordDao.save(queryRecord);
                //需要对可能存在的推荐码以及邀请人进行积分
                VipOrderDO vipOrderDO = orderDao.findOrderByTradeNoAndDeletedFalse(queryRecord.getTradeNo());
                operatorService.updateHistoryScore(vipOrderDO);
            }

            OrgVipRecordDO orgVipRecord = orgVipRecordDao.findRecordByOrganizationIdAndDeletedFalse(order.getOrganizationId());
            if (ObjectUtils.isEmpty(orgVipRecord)) {
                orgVipRecord = new OrgVipRecordDO();
                orgVipRecord.setOrganizationId(order.getOrganizationId());
                orgVipRecord.setTotalSearchTimes(detail.getQueryTotalNum());
                orgVipRecord.setAccountNum(detail.getAccountNum());
                orgVipRecord.setExpiresTime(detail.getExpiresTime());
                orgVipRecord.setBuyAlipayAppletSearchTimes(detail.getQueryTotalNum());
                orgVipRecordDao.save(orgVipRecord);
            } else {
                orgVipRecord.setTotalSearchTimes(orgVipRecord.getTotalSearchTimes() + detail.getQueryTotalNum());
                orgVipRecord.setBuyAlipayAppletSearchTimes((orgVipRecord.getBuyAlipayAppletSearchTimes() == null ? 0 : orgVipRecord.getBuyAlipayAppletSearchTimes()) + detail.getQueryTotalNum());
                if (!ObjectUtils.isEmpty(detail.getDuration())) {
                    Calendar c = Calendar.getInstance();
                    c.setTime(ObjectUtils.isEmpty(orgVipRecord.getExpiresTime()) ? new Timestamp(System.currentTimeMillis()) : orgVipRecord.getExpiresTime());
                    c.add(Calendar.YEAR, detail.getDuration());
                    orgVipRecord.setExpiresTime(new Timestamp(c.getTimeInMillis()));
                }
                if (orgVipRecord.getAccountNum() == null || (!ObjectUtils.isEmpty(detail.getAccountNum()) && orgVipRecord.getAccountNum() < detail.getAccountNum())) {
                    orgVipRecord.setAccountNum(detail.getAccountNum());
                }
                orgVipRecordDao.save(orgVipRecord);
            }

            return "success";
        } else {
            String payTimeStr = params.get("gmt_payment");
            Timestamp payTime = TimeUtil.transferTime(payTimeStr, Regulation.WHOLE_TIME);

            order.setPayTime(payTime);
            order.setState(tradeStatus);
            order.setPayState(PayState.FAILURE);
            orderDao.save(order);

            detail.setPayTime(payTime);
            orderDetailDao.save(detail);

            return "fail";
        }
    }

    @Override
    public String callOrderByAlipayAppletForMembershipCard(HttpServletRequest request) {

        LinkedHashMap<String, String> params = aliAppletService.callOrderForMembershipCard(request);
        if (CollectionUtils.isEmpty(params)) {
            return "fail";
        }

        String outTradeNo = params.get("out_trade_no");
        String tradeStatus = params.get("trade_status");
        if (StringUtils.isBlank(outTradeNo) || StringUtils.isBlank(tradeStatus)) {
            return "fail";
        }
        //保存交易信息
        VipOrderNotifyDO notify = new VipOrderNotifyDO();
        notify.setTradeNo(outTradeNo);
        notify.setResult(GSON.toJson(params));
        orderNotifyDao.save(notify);

        VipOrderDO order = orderDao.findOrderByTradeNoAndDeletedFalse(outTradeNo);
        if (ObjectUtils.isEmpty(order)) {
            log.info("订单号: {} 对应订单不存在", outTradeNo);
            return "fail";
        }
        VipOrderDetailDO detail = orderDetailDao.findDetailByOrderIdAndDeletedFalse(order.getId());
        if (ObjectUtils.isEmpty(detail)) {
            log.info("订单 id : {}, 订单号: {} 详情不存在", order.getId(), order.getTradeNo());
            return "fail";
        }

        if (PayState.SUCCESS.equals(order.getPayState())) {
            log.info("订单号: {} 已支付", outTradeNo);
            return "success";
        }

        if (StringUtils.isNotBlank(outTradeNo) && StringUtils.isNotBlank(tradeStatus)) {
            String payTimeStr = params.get("gmt_payment");
            Timestamp payTime = TimeUtil.transferTime(payTimeStr, Regulation.WHOLE_TIME);
            order.setPayTime(payTime);
            order.setState(tradeStatus);
            order.setPayState(PayState.SUCCESS);
            orderDao.save(order);

            detail.setPayTime(payTime);
            detail.setEffectiveTime(payTime);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(Regulation.WHOLE_TIME);
            LocalDateTime dateTime = LocalDateTime.parse(payTimeStr, formatter);
            detail.setExpiresTime(ObjectUtils.isEmpty(detail.getDuration()) ? null : Timestamp.valueOf(dateTime.plus(detail.getDuration(), ChronoUnit.YEARS)));
            orderDetailDao.save(detail);

            MembershipCardDO membershipCard = membershipCardDao.findInfoByIdAndIsDeletedFalse(order.getVipId());
            log.info("会员卡优惠价格: {}", membershipCard.getDiscountFee());
            MembershipCardAccountDO membershipCardAccount = membershipCardAccountDao.findInfoByAccountIdAndMembershipCardId(order.
                    getCreatorId(), membershipCard.getId());

            if (membershipCardAccount == null) {
                membershipCardAccount = new MembershipCardAccountDO();
                membershipCardAccount.setAccountId(order.getCreatorId());
                membershipCardAccount.setMembershipCardId(membershipCard.getId());
                membershipCardAccount.setDiscountFee(membershipCard.getDiscountFee());
                Date now = new Date();
                membershipCardAccount.setExpireTime(addDaysToDate(now, membershipCard.getValidDays()));
                membershipCardAccount.setTradeNoInfos(outTradeNo);
                membershipCardAccountDao.save(membershipCardAccount);
            } else {
                membershipCardAccount.setTradeNoInfos(membershipCardAccount.getTradeNoInfos() + "," + outTradeNo);
                Date expireTime = membershipCardAccount.getExpireTime();
                membershipCardAccount.setExpireTime(addDaysToDate(expireTime, membershipCard.getValidDays()));
                membershipCardAccount.setDiscountFee(membershipCard.getDiscountFee());
                membershipCardAccountDao.save(membershipCardAccount);
            }
            return "success";
        } else {
            String payTimeStr = params.get("gmt_payment");
            Timestamp payTime = TimeUtil.transferTime(payTimeStr, Regulation.WHOLE_TIME);

            order.setPayTime(payTime);
            order.setState(tradeStatus);
            order.setPayState(PayState.FAILURE);
            orderDao.save(order);

            detail.setPayTime(payTime);
            orderDetailDao.save(detail);

            return "fail";
        }

    }

    public static Date addDaysToDate(Date start, int days) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(start); // 设置当前时间为给定的时间
        calendar.add(Calendar.DAY_OF_MONTH, days); // 添加天数
        return calendar.getTime(); // 返回新的日期
    }

    @Override
    public List<MembershipCardSimpleVO> getMembershipCardOrderInfo(Integer cardType) {
        List<MembershipCardSimpleVO> result = new ArrayList<>();
        List<MembershipCardDO> membershipCards = membershipCardDao.findInfoByCardTypeAndIsDeletedFalse(cardType);
        if (CollectionUtils.isEmpty(membershipCards)) {
            return result;
        }
        for (MembershipCardDO membershipCard : membershipCards) {
            MembershipCardSimpleVO cardSimple = new MembershipCardSimpleVO();
            cardSimple.setId(membershipCard.getId());
            cardSimple.setCardName(membershipCard.getCardName());
            cardSimple.setCardFee(membershipCard.getCardFee());
            cardSimple.setCardType(membershipCard.getCardType());
            if (membershipCard.getValidDays() != null) {
                cardSimple.setValidYear(membershipCard.getValidDays() / 365);
            }
            cardSimple.setQueryNum(membershipCard.getQueryNum());
            cardSimple.setAccountNum(membershipCard.getAccountNum());
            result.add(cardSimple);
        }
        return result;
    }

    @Override
    public String addByAlipayQrcode(Long accountId, AddOrderForm form) {

        VipInfoDO vipInfo = vipInfoDao.findByIdAndDeletedFalse(form.getVipId());
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(vipInfo), VipExceptionEnum.VIP_NOT_EXIST);
        AccountDO account = accountDao.findByIdAndDeletedFalse(accountId);
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(account), AccountExceptionEnum.ACCOUNT_NOT_EXIST);
        UserInfoDO userInfo = userInfoDao.findByIdAndDeletedFalse(account.getUserId());
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(userInfo), UserExceptionEnum.USER_NOT_EXIST);
        OrganizationDO organization = organizationDao.findByIdAndDeletedFalse(account.getOrganizationId());
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(organization), OrganizationExceptionEnum.ORGANIZATION_NOT_EXIST);

        String tradeNo = UUID.randomUUID().toString().replace("-", "");
        String response = apiQrcodeAliPayService.addOrder(new AddOrderDTO(tradeNo, vipInfo.getName(), vipInfo.getTotalPrice(), null));

        VipOrderDO order = new VipOrderDO();
        order.setVipId(form.getVipId());
        order.setVipName(vipInfo.getName());
        order.setOrganizationId(account.getOrganizationId());
        order.setTradeNo(tradeNo);
        order.setTotalPrice(vipInfo.getTotalPrice());
        order.setExpiresTime(new Timestamp(System.currentTimeMillis() + 2 * 60 * 60 * 1000));
        order.setPayState(PayState.TO_PAY);
        order.setOrgType(organization.getType());
        orderDao.save(order);
        VipOrderDetailDO detail = new VipOrderDetailDO();
        detail.setOrderId(order.getId());
        detail.setTradeNo(tradeNo);
        detail.setVipName(vipInfo.getName());
        detail.setTotalPrice(vipInfo.getTotalPrice());
        detail.setUnitPrice(vipInfo.getUnitPrice());
        detail.setDuration(vipInfo.getDuration());
        detail.setQueryTotalNum(vipInfo.getQueryTotalNum());
        detail.setAccountNum(vipInfo.getAccountNum());
        detail.setOrgName(OrganizationType.ENTER.equals(organization.getType()) ? organization.getEnterName() : account.getUsername());
        detail.setUsername(account.getUsername());
        detail.setPhone(userInfo.getPhone());
        detail.setType("支付宝");
        detail.setOrgType(organization.getType());
        orderDetailDao.save(detail);
        log.info("创建二维码支付宝支付订单号: {}, 订单参数：{}", tradeNo, response);
        return response;
    }

    @Override
    public String callOrderByAlipayQrcode(HttpServletRequest request) {

        LinkedHashMap<String, String> params = apiQrcodeAliPayService.callOrder(request);
        if (CollectionUtils.isEmpty(params)) {
            return "fail";
        }

        String outTradeNo = params.get("out_trade_no");
        String tradeStatus = params.get("trade_status");
        if (StringUtils.isBlank(outTradeNo) || StringUtils.isBlank(tradeStatus)) {
            return "fail";
        }

        //保存交易信息
        VipOrderNotifyDO notify = new VipOrderNotifyDO();
        notify.setTradeNo(outTradeNo);
        notify.setResult(GSON.toJson(params));
        orderNotifyDao.save(notify);

        VipOrderDO order = orderDao.findOrderByTradeNoAndDeletedFalse(outTradeNo);
        if (ObjectUtils.isEmpty(order)) {
            log.info("订单号: {} 对应订单不存在", outTradeNo);
            return "fail";
        }
        VipOrderDetailDO detail = orderDetailDao.findDetailByOrderIdAndDeletedFalse(order.getId());
        if (ObjectUtils.isEmpty(detail)) {
            log.info("订单 id : {}, 订单号: {} 详情不存在", order.getId(), order.getTradeNo());
            return "fail";
        }

        if (PayState.SUCCESS.equals(order.getPayState())) {
            log.info("订单号: {} 已支付", outTradeNo);
            return "success";
        }

        if (StringUtils.isNotBlank(outTradeNo) && StringUtils.isNotBlank(tradeStatus)) {
            String payTimeStr = params.get("gmt_payment");
            Timestamp payTime = TimeUtil.transferTime(payTimeStr, Regulation.WHOLE_TIME);
            order.setPayTime(payTime);
            order.setState(tradeStatus);
            order.setPayState(PayState.SUCCESS);
            orderDao.save(order);

            detail.setPayTime(payTime);
            detail.setEffectiveTime(payTime);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(Regulation.WHOLE_TIME);
            LocalDateTime dateTime = LocalDateTime.parse(payTimeStr, formatter);
            detail.setExpiresTime(ObjectUtils.isEmpty(detail.getDuration()) ? null : Timestamp.valueOf(dateTime.plus(detail.getDuration(), ChronoUnit.YEARS)));
            orderDetailDao.save(detail);

            QueryRecordDO queryRecord = queryRecordDao.findByTradeNoAndDeletedFalse(outTradeNo);
            if (queryRecord != null && SearchType.ENTERPRISE.equals(queryRecord.getType())) {
                queryRecord.setAuthorizedResult(AuthResultType.AUTHORIZED);
                queryRecord.setShow(true);
                queryRecordDao.save(queryRecord);
            }

            OrgVipRecordDO orgVipRecord = orgVipRecordDao.findRecordByOrganizationIdAndDeletedFalse(order.getOrganizationId());
            if (ObjectUtils.isEmpty(orgVipRecord)) {
                orgVipRecord = new OrgVipRecordDO();
                orgVipRecord.setOrganizationId(order.getOrganizationId());
                orgVipRecord.setTotalSearchTimes(detail.getQueryTotalNum());
                orgVipRecord.setAccountNum(detail.getAccountNum());
                orgVipRecord.setExpiresTime(detail.getExpiresTime());
                orgVipRecord.setBuyAlipayAppletSearchTimes(detail.getQueryTotalNum());
                orgVipRecordDao.save(orgVipRecord);
            } else {
                orgVipRecord.setTotalSearchTimes(orgVipRecord.getTotalSearchTimes() + detail.getQueryTotalNum());
                orgVipRecord.setBuyAlipayAppletSearchTimes((orgVipRecord.getBuyAlipayAppletSearchTimes() == null ? 0 : orgVipRecord.getBuyAlipayAppletSearchTimes()) + detail.getQueryTotalNum());
                if (!ObjectUtils.isEmpty(detail.getDuration())) {
                    Calendar c = Calendar.getInstance();
                    c.setTime(ObjectUtils.isEmpty(orgVipRecord.getExpiresTime()) ? new Timestamp(System.currentTimeMillis()) : orgVipRecord.getExpiresTime());
                    c.add(Calendar.YEAR, detail.getDuration());
                    orgVipRecord.setExpiresTime(new Timestamp(c.getTimeInMillis()));
                }
                if (orgVipRecord.getAccountNum() == null || (!ObjectUtils.isEmpty(detail.getAccountNum()) && orgVipRecord.getAccountNum() < detail.getAccountNum())) {
                    orgVipRecord.setAccountNum(detail.getAccountNum());
                }
                orgVipRecordDao.save(orgVipRecord);
            }
            //直接创建查询个人记录(一体机没有使用，此段代码隐掉)
//            Long organizationId = order.getOrganizationId();
//            AccountDO account = accountDao.findAccountByOrganizationIdAndDeletedFalse(organizationId).get(0);
//            UserInfoDO userInfo = userInfoDao.findByIdAndDeletedFalse(account.getUserId());
//            AddSearchRecordForm addSearchRecord = new AddSearchRecordForm();
//            SearchRecordContentDTO searchRecordContent = new SearchRecordContentDTO();
//            searchRecordContent.setName(userInfo.getUserName());
//            searchRecordContent.setPhone(userInfo.getPhone());
//            searchRecordContent.setIdNumber(userInfo.getCertNo());
//            addSearchRecord.setContent(searchRecordContent);
//            addSearchRecord.setType(SearchType.PERSON);
//            searchRecordService.add(account.getId(), addSearchRecord);
//            SendAuthorizedCodeForm sendAuthorizedCode = new SendAuthorizedCodeForm();
//            sendAuthorizedCode.setName(userInfo.getUserName());
//            sendAuthorizedCode.setPhone(userInfo.getPhone());
//            sendAuthorizedCode.setIdNumber(userInfo.getCertNo());
//            sendAuthorizedCode.setTradeNo(order.getTradeNo());
//            smsService.sendAuthorizedCodeBySelf(account.getId(), sendAuthorizedCode);
            return "success";
        } else {
            String payTimeStr = params.get("gmt_payment");
            Timestamp payTime = TimeUtil.transferTime(payTimeStr, Regulation.WHOLE_TIME);

            order.setPayTime(payTime);
            order.setState(tradeStatus);
            order.setPayState(PayState.FAILURE);
            orderDao.save(order);

            detail.setPayTime(payTime);
            orderDetailDao.save(detail);

            return "fail";
        }
    }

    public static Config open_config;
    public static final String PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAi/7rUBi4mm2rHzSW0BLey52A69zvbXiE7gz0bvqSKKJSSpLdvBZxhseQBSuUoaOSNzmna5ov1uu0pYC1vWGHsf7YjzcrAl8aYBL+wpVAsjij+fLTeftYleVZZPjIZfGtrggDuO3L4vVrmyszOqRFS9063jy4xnfYsBwXJjmaw2vmXx6BFE+WKAmytgcopk44Jt9HZqezRtV0HcuMnBYfXW1s/9/blqNpphzpk8tWBeb9/kE0gZ2+SkLqU2Gpnn/ImeOWRs5yDKYAOYDec8AAABPGo6F3MRNAX2OSkhce1lnZV9VQvwiotbg5Az8IftwYWVyTXPqOfv/++kj5psyPnQIDAQAB";

    public static Config getOptions() {
        if (open_config == null) {
            Config config = new Config();
            config.protocol = "https";
            config.gatewayHost = "openapi.alipay.com";
            config.signType = "RSA2";
            config.appId = "2021004108624309";
            config.merchantPrivateKey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCX2eLcNJr+0R8oaELOmk+iiVXA1bOrI6iVAiJAM56icWDIJ9boG57JOPOSPXv1NjrtecRdAWePxkCRePUzLbkiy7zELotHktXTruyGQJSzDuHDIAo686SONlu5jT886o8foPYRrMVi3m/e/Y1c1VcE7qVt0i6BGgUgLkwI/8/6asvAp1pwgw7IlLRvDK+nrS+X0zad6vC0RrZcTo5/YaRCDvdxfJsIzPElRbddy8TfyblXk/RtgWjP1AnnLcz/tHItrt75iep/Ij8lDJ6S2tea4XBjzFtwrG1zmE+livATl6U6HFvNUu0U63vD8PzE9JnP2IknS6DQWfHI9vq4QFYtAgMBAAECggEAHu6tfbnhkOK8fBiw8zEP48YiB8QAc24yGxhyLa3WNLTvyBYFewaVU9wcEcAgjhTb8CAL1f5BQFJcOMXw/NnliqcB7tykVpIcqKBLYhWptMflSUAvlU6oSKfeC3AwX5JQUVsShQsysi8pjr0LnMuAjGqonDRicL4CKUoFBxhFH3dtTOOkbBeCUhWl2fBAareZ1H9b/jjMg/5eCUXpx1rNTg6dkR1zeWfPvTh8BmUtq0CQQSzXuGnkL2q1JysBQa1aWZEUt2Y9m+mL1qiJfuXaL1hQ2x8R2NjRoHHpUlR99qNB/hPq5SHznlEb2XVUgu9cOzUNhjQrmNNwmTSTzwaHqQKBgQDRa9Vp6TvGbZi3ffPbDzvU4EhcLy38q3Co0hrKaM7PYWYpa4I9zdXATuRqtZOzUGnUOGGAHTcNB6avmR7aasDNBy1HkILgj/ehDhRbbvcF8Tvj/pFn8lvYgVeq70zeqb8KYgae5LfR536FzZ3WDe+zsawbI5wMJM1CYBWmj924PwKBgQC5oBZLz7oP/FUBIU22DHUaNPgb3oToIVOAfOUfw33qwpfInvHgiAdQplvoASJmAMb02emHqEcMe6+fr6lOddYm4Ldk2mC5lXBYqyepluHD/IQQLxQey2O/r0KkZoMYmhuh1j7ozTTOi31B2Z1mwf2DT+Q8tTkxFszlx9E9Yl32kwKBgDeybEIMy98MSu+SSgba2FjXhacuzRZEKmRb7NAka8xv5RHjC/KQCedplAplXHD2VA8jJ5tBKeEHReex26jPd5OP8xTzdDtxTrTA390pd/1WmU0b6WQx6wd77usBVfpqPuruA0DDJ7hlzxqbAv1pG3U5LcLSB7CbIRQkJd30qU1VAoGBAJn+TiDsnt4eJuL+HvsVUJzCLsboDniJFT313xs/0hlNACCmg+ES2Ia2zG4nasMWh/efRFaPawnXHnaqgxmdNmEgceSQKkgryn002H2ft4Ig3eqTM+zsLL9cBTxf8wgY6S2UkLIPc2yaWfqkLymNa+RhBea7LUwlLyy9XT/AeFVTAoGAbDxZzdNKRfhwiJNlhsB5sutgew8b8VSygXYPQgoG/yzHvSKe4UygcrgJggAl6xNRoNFgkVF1QDGSAG4kak7WFjDo4M878Qgsg392RZfllKy45nxBfL91yPGogMAnsy+3kBQZRP0stRbabIXlCua/yZm6PTTYjtFf78mvrSinnhQ=";
            config.alipayPublicKey = PUBLIC_KEY;
            //可设置异步通知接收服务地址（可选）
//            config.notifyUrl = "https://cxb.learncoder.com:8901/api/order/notify/app/ali";
            //   config.notifyUrl = "https://admin.njxnet.com:8901/api/order/notify/code/ali";
            config.notifyUrl = "https://admin.njxnet.com:8901/api/order/notify/code/ali";
            // config.notifyUrl = "http://yuantu.natapp1.cc/api/order/notify/code/ali";
            //可设置AES密钥，调用AES加解密相关接口时需要（可选）
            config.encryptKey = "7qe0WUf9GVnfj/5qPGpmNA==";
            return config;
        } else {
            return open_config;
        }
    }

    @Override
    public String addByAlipayQrcodeTest() {

        Factory.setOptions(getOptions());
        try {
            Client pageClient = Factory.Payment.Page();
            pageClient.optional("qr_pay_mode", "1");
            AlipayTradePagePayResponse response = pageClient.pay("测试商品001", UUID.randomUUID().toString().
                    replace("-", ""), "0.01", null);
            if (ResponseChecker.success(response)) {
                System.out.println(response.getBody());
            } else {
                log.info("二维码支付宝支付-创建订单失败，返回值：{}", GSON.toJson(response));
            }
        } catch (Exception e) {
            log.error("二维码支付宝支付-创建订单异常，原因：" + e.getMessage(), e);
        }
        return null;
    }

    private final String url = "jdbc:mysql://localhost:3306/judicial_data?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&useSSL=false";
    private final String user = "root";
    private final String password = "zzw";

    @Override
    public void testQuery(Long orderId) {
        VipOrderDO order = orderDao.findOrderByIdAndDeletedFalse(orderId);
        order.setPayState(PayState.SUCCESS);
        VipOrderDO existOrder = orderDao.findOrderByIdAndDeletedFalse(orderId);
        System.out.println(existOrder.getPayState().toString());
        Connection conn = null;
        Statement stat = null;
        try {
            conn = DriverManager.getConnection(url, user, password);
            stat = conn.createStatement();
            String sql = "select * from vip_order where id = " + orderId;
            ResultSet rs = stat.executeQuery(sql);
            if (rs.next()) {
                System.out.println(rs.getString("pay_state"));
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (stat != null) {
                try {
                    stat.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    @Override
    public Boolean getMembershipCardShowInfo() {
        ShowInfoDO showInfo = showInfoDao.findShowInfo();
        if (showInfo != null) {
            return showInfo.getIsShow();
        }
        return false;
    }

}
